<template>
  <base-container class="add-container h-full" v-loading="loading">
    <div class="celling-top" v-if="showTop">
      <info-nav :current-step="step" />
    </div>
    <info-nav :current-step="step" />
    <info-classification ref="classificationRef" />
    <info-intel ref="productInfoRef" />
    <info-rental-setting ref="rentRef" :plan-data="planData" />
    <info-plan ref="planRef" :plan-data="planData" />
    <div class="add-btn">
      <el-space :size="16">
        <el-button @click="saveProduct">暂存内容</el-button>
        <el-button type="primary" @click="handleBeforeAdd">立即发布</el-button>
      </el-space>
    </div>
  </base-container>
</template>

<script setup>
  import infoNav from "./componets/product-info-modules/InfoNav.vue";
  import InfoClassification from "./componets/product-info-modules/InfoClassification.vue";
  import InfoIntel from "./componets/product-info-modules/InfoIntel.vue";
  import InfoRentalSetting from "./componets/product-info-modules/InfoRentalSetting.vue";
  import InfoPlan from "./componets/product-info-modules/InfoPlan.vue";
  // 需要获取的字典
  const dictCodeGroup = [
    "qingyun.product.rent.sale.type", // 租售类型
    "qingyun.product.product.type", // 商品类型
    "qingyun.product.new.old.degree", // 新旧成色
    "qingyun.product.rent.object.type", // 租赁对象
    "qingyun.product.channel.type", // C端渠道
    "qingyun.product.rent.plan", // 渠道方案
    "qingyun.product.rent.model.type", //  租赁模式
    "qingyun.product.return.rule", // 归还规则
    "qingyun.product.buy.out.rule", // 租售类型
    "qingyun.product.rent.sale.type", // 买断规则
    "qingyun.product.delivery.postage.type", // 发货邮费
    "qingyun.product.return.postage.type", // 归还邮费
    "qingyun.product.zhima.detail.style", // 芝麻租物商品详情页样式
    "qingyun.product.zhima.automatic", // 芝麻租物自动推广
    "qingyun.product.lease.term", // 租期天数
    "qingyun.product.delivery.postage.type", // 发货邮费
    "qingyun.product.return.postage.type", //  归还邮费
    "qingyun.support.customer.additionalServices", // 增值服务类型
  ];
  // 获取全局方法
  const App = useGlobals();
  // 路由实例
  const router = useRouter();
  const route = useRoute();
  // 所有字典数据
  const allConfigData = ref([]);
  // 类目属性数据
  const classAttrList = ref([]);
  // 类目Ref
  const classificationRef = ref();
  // 商品信息Ref
  const productInfoRef = ref();
  // 租赁设置Ref
  const rentRef = ref();
  // 租赁方案Ref
  const planRef = ref();
  // 物流Ref
  const logisticalRef = ref();
  // 方案列表
  const planData = ref([]);
  // 商品详情
  const productDetail = ref({});
  //
  const loading = ref(false);
  // 是否编辑
  const isEdit = ref(false);
  const scrollbarCtx = inject("LayoutMainScrollbar", null);
  // 当前tab
  const step = ref(1);
  // 显示吸顶
  const showTop = ref(false);
  // 需要挽留
  const needRetain = ref(true);
  function handleScroll(e) {
    const target = e.target;
    const { scrollTop, scrollHeight, clientHeight } = target;
    const scrollData = [
      { step: 1, distance: classificationRef.value.getTop().offsetTop - scrollTop },
      { step: 2, distance: productInfoRef.value.getTop().offsetTop - scrollTop },
      { step: 3, distance: rentRef.value.getTop().offsetTop - scrollTop },
      { step: 4, distance: planRef.value.getTop().offsetTop - scrollTop },
    ];
    // 是否展示吸顶
    if (scrollTop > 200 && !showTop.value) {
      showTop.value = true;
    }
    if (scrollTop < 200 && showTop.value) {
      showTop.value = false;
      step.value = 1;
    }
    if (scrollTop + clientHeight >= scrollHeight - 10) {
      step.value = 5;
      return;
    }
    // 判断当前滚动
    for (let i = 0; i < scrollData.length; i++) {
      if (scrollData[i].distance > -100 && scrollData[i].distance < 200) {
        step.value = scrollData[i].step;
        break;
      }
    }
  }

  let removeListener = null;
  // 初始化
  onMounted(() => {
    console.warn(route.query.id, "9999999999");
    console.log("🚀 ~ scrollbarCtx:", scrollbarCtx);
    if (!scrollbarCtx) {
      console.warn("未获取到 layoutMainScrollbarRef");
      return;
    }
    // 立即尝试绑定（若 wrap 还没准备好，可再做一次延迟）
    removeListener = scrollbarCtx.onMainScroll(handleScroll);
    // 可选：若第一次时 wrap 还为空，可 setTimeout 重试
    if (!scrollbarCtx.getWrapEl()) {
      setTimeout(() => {
        if (!removeListener) removeListener = scrollbarCtx.onMainScroll(handleScroll);
      }, 50);
    }
    // 获取详情
    if (route.query.id) {
      isEdit.value = true;
      loadProductDetail();
    }
    loadAllConfigData();
  });
  // 批量获取字典配置数据
  const loadAllConfigData = () => {
    Api.common.getMultipleDictionaryData({ dictCodes: dictCodeGroup }).then(res => {
      console.warn(res);
      allConfigData.value = res.data;
    });
  };
  // 获取指定字典数据
  const getConfig = code => {
    if (allConfigData.value.length) {
      const currentConfig = allConfigData.value.find(el => el.dictCode === code);
      return currentConfig ? currentConfig.childList : [];
    }
    return [];
  };
  // 获取商品详情
  const loadProductDetail = () => {
    loading.value = true;
    Api.product.getProductDetail({ id: route.query.id }).then(res => {
      loading.value = false;
      productDetail.value = res.data;
    });
  };
  // 子组件获取指定字典数据方法
  provide("getConfig", getConfig);
  // 类目属性数据
  provide("classAttrList", classAttrList);
  // 详情
  provide("detail", productDetail);
  // 提交前验证
  const handleBeforeAdd = async () => {
    const classificationVerifyRes = await classificationRef.value.formVerify();
    const productInfoVerifyRes = await productInfoRef.value.formVerify();
    const rentVerifyRes = await rentRef.value.formVerify();
    const planVerifyRes =
      rentRef.value.rentalForm.rentPlan === "1"
        ? await planRef.value.formVerifySingle()
        : await planRef.value.formVerifyMutiple();
    // 参数处理
    if (classificationVerifyRes && productInfoVerifyRes && rentVerifyRes && planVerifyRes) {
      // 商品类目
      const classificationParams = classificationRef.value.classificationForm;
      // 商品信息
      const productInfoParams = productInfoRef.value.infoForm;
      // 租赁设置
      const rentParams = rentRef.value.rentalForm;
      // 租赁设置---选择部分渠道且方案选择指定方案校验所选渠道是否有效
      if (rentParams.channelType === "2" && rentParams.rentPlan === "2") {
        const allChannel = [];
        rentParams.productRentPlanList.forEach(item => {
          allChannel.push(...item.planChannelList);
        });
        const channelExist = allChannel.every(item => {
          return rentParams.channelList.find(el => el.id === item.id);
        });
        if (!channelExist) {
          $msg.warning("租赁方案--指定方案请选择有效的渠道");
          return;
        }
      }
      // 方案数据
      const productRentPlanList = [];
      // 方案设置处理
      if (rentParams.rentPlan === "1") {
        // 统一方案（单个）
        // 方案设置
        const planParams = planRef.value.unifiedPlanRef.planSettingForm;
        // 物流信息
        const logisticalParams = planRef.value.unifiedPlanRef.getLogistiParams();
        const productSpecAssociation = {
          chooseSpecList: planRef.value.unifiedPlanRef.checkParenAttr,
          allSpecList: planRef.value.unifiedPlanRef.optionalAttrList.map(el => el.id),
          productAttributeList: planRef.value.unifiedPlanRef.optionalAttrList.map(el => {
            return { id: el.id, childrenIdList: el.subsets.map(el => el.id) };
          }),
        };
        const productSkuList = planParams.productSkuList.map(item => {
          const productSkuPriceList = [];
          for (let key in item.rentDay) {
            if (!item.rentDay[key].disabled) {
              const priceItem = {
                shortChoose: 0,
                days: key,
                dayPrice: item.rentDay[key].dayPrice,
                underlinePrice: item.rentDay[key].underlinePrice,
                salePrice: item.rentDay[key].salePrice,
              };
              productSkuPriceList.push(priceItem);
            }
          }
          return {
            imageUrl: item.imageUrl[0],
            hideFlag: item.hideFlag,
            officialPrice: item.officialPrice,
            purchasePrice: item.purchasePrice,
            quantity: item.quantity,
            productSkuSpecList: item.allSkus.map(el => el.id),
            productRentModelTypeList: [{ rentModelType: item.rentModelType, productSkuPriceList }],
          };
        });
        const planItem = {
          ...planParams,
          ...logisticalParams,
          productSkuList,
          productSpecAssociation,
          periodDays: planParams.periodType === 2 ? planParams.periodDays : "",
        };
        delete planItem.chooseSpecList;
        delete planItem.areaList;
        productRentPlanList.push(planItem);
      } else {
        // 指定方案（多个）
        console.warn(planRef.value.allPlanData, "统一");
        productRentPlanList.push(...planRef.value.allPlanData);
      }
      const params = {
        firstCategoryId: classificationParams.category[0],
        secondCategoryId: classificationParams.category[1],
        brandId: classificationParams.category[2],
        modelId: classificationParams.category[3],
        ...productInfoParams,
        videoUrl: productInfoParams.videoUrl[0],
        productParameterList: productInfoParams.productParameterList,
        productComponentList: productInfoParams.productComponentList?.map(el => {
          const { id, quantity, amount } = el;
          return { id, quantity, amount };
        }),
        productAdditionalServicesList: productInfoParams?.productAdditionalServicesList?.map(el => el.id),
        ...rentParams,
        priceRatio: !rentParams.rentObjectList?.includes("2") ? "" : rentParams.priceRatio,
        channelList: rentParams.channelList?.map(el => el.id),
        productRentPlanList,
      };
      console.warn(params);
      if (isEdit.value) {
        params.id = productDetail.value.id;
        handelUpdateProduct(params);
        return;
      } else {
        handleAddProduct(params);
      }
    }
  };
  // 暂存处理
  const saveProduct = () => {
    // 商品类目
    const classificationParams = classificationRef.value.classificationForm;
    // 商品信息
    const productInfoParams = productInfoRef.value.infoForm;
    // 租赁设置
    const rentParams = rentRef.value.rentalForm;

    // 方案数据
    const productRentPlanList = [];
    if (rentParams.rentPlan === "1") {
      // 统一方案（单个）
      // 方案设置
      const planParams = planRef.value.unifiedPlanRef.planSettingForm;
      // 物流信息
      const logisticalParams = planRef.value.unifiedPlanRef.getLogistiParams();
      const productSpecAssociation = {
        chooseSpecList: planRef.value.unifiedPlanRef.checkParenAttr,
        allSpecList: planRef.value.unifiedPlanRef.optionalAttrList?.map(el => el.id),
        productAttributeList: planRef.value.unifiedPlanRef.optionalAttrList?.map(el => {
          return { id: el.id, childrenIdList: el.subsets?.map(el => el.id) };
        }),
      };
      const productSkuList = planParams.productSkuList?.map(item => {
        const productSkuPriceList = [];
        for (let key in item.rentDay) {
          if (!item.rentDay[key].disabled) {
            const priceItem = {
              shortChoose: 0,
              days: key,
              dayPrice: item.rentDay[key].dayPrice,
              underlinePrice: item.rentDay[key].underlinePrice,
              salePrice: item.rentDay[key].salePrice,
            };
            productSkuPriceList.push(priceItem);
          }
        }
        return {
          imageUrl: item?.imageUrl[0],
          hideFlag: item.hideFlag,
          officialPrice: item.officialPrice,
          purchasePrice: item.purchasePrice,
          quantity: item.quantity,
          productSkuSpecList: item.allSkus?.map(el => el.id),
          productRentModelTypeList: [{ rentModelType: item.rentModelType, productSkuPriceList }],
        };
      });
      const planItem = {
        ...planParams,
        ...logisticalParams,
        productSkuList,
        productSpecAssociation,
        periodDays: planParams.periodType === 2 ? planParams.periodDays : "",
      };
      delete planItem.chooseSpecList;
      delete planItem.areaList;
      productRentPlanList.push(planItem);
    } else {
      // 指定方案（多个）
      console.warn(planRef.value.allPlanData, "统一");
      productRentPlanList.push(...planRef.value.allPlanData);
    }
    const params = {
      firstCategoryId: classificationParams?.category[0],
      secondCategoryId: classificationParams?.category[1],
      brandId: classificationParams?.category[2],
      modelId: classificationParams?.category[3],
      ...productInfoParams,
      videoUrl: productInfoParams?.videoUrl[0],
      productParameterList: productInfoParams?.productParameterList,
      productComponentList: productInfoParams.productComponentList?.map(el => {
        const { id, quantity, amount } = el;
        return { id, quantity, amount };
      }),
      productAdditionalServicesList: productInfoParams?.productAdditionalServicesList?.map(el => el.id),
      ...rentParams,
      priceRatio: !rentParams.rentObjectList?.includes("2") ? "" : rentParams.priceRatio,
      channelList: rentParams.channelList?.map(el => el.id),
      productRentPlanList,
    };
    console.warn(params);
    handleSave(params);
  };
  // 暂存内容
  const handleSave = params => {
    needRetain.value = false;
    Api.product.saveProduct(params).then(res => {
      $msg.success("操作成功");
      router.push({ path: "/product/product-list" });
    });
  };
  // 新增
  const handleAddProduct = params => {
    needRetain.value = false;
    Api.product.addProduct(params).then(res => {
      $msg.success("新增成功");
      router.push({ path: "/product/product-list" });
    });
  };
  // 编辑
  const handelUpdateProduct = params => {
    needRetain.value = false;
    Api.product.editProduct(params).then(res => {
      $msg.success("操作成功");
      router.push({ path: "/product/product-list" });
    });
  };
  onBeforeRouteLeave(async (to, from, next) => {
    if (!needRetain.value) {
      return next(true);
    }
    return App.$confirm("离开页面可能导致已填写内容丢失，确定要离开吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        next(true);
      })
      .catch(() => {
        next(false);
      });
  });
</script>

<style lang="scss" scoped>
  .add-container {
    position: relative;
    padding-bottom: 88px;
    .info-box {
      position: absolute;
      top: 0;
      left: 0;
    }
    .add-btn {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 72px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--fl7);
    }
    .celling-top {
      position: sticky;
      top: 0;
      width: 100%;
      z-index: 9;
      border-radius: 12px;
      box-shadow: 0px 2px 4px 0px #0000000d;
    }
  }
</style>
